package com.ruoyi.demo.service.impl

import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.kotlin.extensions.condition.and
import com.mybatisflex.kotlin.extensions.db.query
import com.mybatisflex.kotlin.extensions.kproperty.eq
import com.mybatisflex.kotlin.extensions.wrapper.whereWith
import com.mybatisflex.spring.service.impl.ServiceImpl
import com.ruoyi.common.core.page.TableSupport
import com.ruoyi.common.exception.ServiceException
import com.ruoyi.common.utils.DateUtils
import com.ruoyi.common.utils.MapstructUtils
import com.ruoyi.common.utils.SecurityUtils
import com.ruoyi.demo.domain.Demo
import com.ruoyi.demo.domain.DemoTest
import com.ruoyi.demo.domain.dto.DemoDTO
import com.ruoyi.demo.domain.dto.DemoTestDTO
import com.ruoyi.demo.mapper.DemoMapper
import com.ruoyi.demo.service.IDemoService
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.stereotype.Service

/**
 * @author LikeYouDo
 * @date 2025/09/23
 */
@Service
class DemoServiceImpl() : ServiceImpl<DemoMapper, Demo>(), IDemoService {

    companion object{
        private val log = KotlinLogging.logger {  }
    }

    override fun listDemo(dto: DemoDTO): Page<Demo> {
        val pageDomain = TableSupport.getPageDomain()
        return this.page(
            Page(pageDomain.pageNum, pageDomain.pageSize),
            // name为null自动忽略条件
            QueryWrapper.create().eq(Demo::name, dto.name)
        )
    }

    override fun queryByCondition(dto: DemoDTO): List<Demo> {
        val demoTest = DemoTest().apply {
            this.id = dto.id
            this.name = dto.name
        }
        val dtDto = DemoTestDTO()
        MapstructUtils.convert(demoTest, dtDto)
        log.info { "dtDto: $dtDto" }
        return query<Demo> {
            whereWith {
                Demo::name eq dto.name and  (Demo::id eq dto.id)
            }
        }
    }

    override fun addDemo(dto: DemoDTO): Boolean {
        require(dto.id == null){
            log.error { "id: ${dto.id}不为空" }
            throw ServiceException("id不为空")
        }
        val demo = Demo().apply {
            MapstructUtils.convert(dto, this)
            this.createBy = SecurityUtils.getUsername()
            this.createTime = DateUtils.getNowDate()
        }

        return this.save(demo)
    }


}